﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Domain.Authentication;
using Cms.Web.Framework.Controls;
using Cms.Web.Framework.Infrastructure;
using iLib.Web.UI;

namespace Cms.Web.UI.Admin
{
    public partial class Admin : AdminMaster, IAdminMasterView
    {
        private AdminMasterPresenter _presenter;
        private RequestDetails _details;

        #region IAdminMasterView Members

        public virtual int AdministratorID
        {
            get
            {
                AuthenticatedUser user = Conversion.ToAuthenticatedUser(Page.User.Identity.Name);
                return user.AdministratorID;
            }
        }

        public void SetAdministratorName(string fullname)
        {
            litAdministratorName.Text = fullname;
        }

        public void SetCurrentSite(string domain)
        {
            litCurrentSite.Text = domain;
            if (domain.ToLower() != Request.Url.Host.ToLower())
            {
                string url = "http://" + domain + "/" + _details.FoldersAndPage;
                if (!string.IsNullOrEmpty(_details.QueryString))
                    url += "?" + _details.QueryString;
                Response.Redirect(url);
            }
        }

        public void SetSystemVersion(string version)
        {
            litSystemVersion.Text = version;
        }

        public void SetSystemCulture(Administrator administrator)
        {
            string cultureCode;
            switch (Request.Form["__EVENTTARGET"])
            {
                case "ctl00$lbEnglish":
                    cultureCode = "en-US";
                    break;
                case "ctl00$lbSwedish":
                    cultureCode = "sv-SE";
                    break;
                default:
                    cultureCode = administrator.DefaultSystemLocale;
                    break;
            }
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureCode);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCode, true);
            var cultureDtfi = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
            var dtfi = new DateTimeFormatInfo
                           {
                               ShortDatePattern = string.IsNullOrEmpty(administrator.DateFormat)
                                                      ? cultureDtfi.ShortDatePattern
                                                      : administrator.DateFormat,
                               ShortTimePattern = string.IsNullOrEmpty(administrator.TimeFormat)
                                                      ? cultureDtfi.ShortTimePattern
                                                      : administrator.TimeFormat,
                               FirstDayOfWeek = administrator.FirstDayOfWeek.HasValue
                                                    ? administrator.FirstDayOfWeek.Value
                                                    : cultureDtfi.FirstDayOfWeek
                           };
            Thread.CurrentThread.CurrentCulture.DateTimeFormat = dtfi;
            Thread.CurrentThread.CurrentUICulture.DateTimeFormat = dtfi;
        }

        public void RedirectToConfigureFirstSite()
        {
            Response.Redirect("~/Admin/ConfigureFirstSite.aspx");
        }

        public void ShowIntroHelp()
        {
            string script = "cms.Dialogs.CustomAlert(null, '" +
                            Translator.GetText(ContextTranslationFile, "IntroHelpHeader", Localization) +
                            "', '" +
                            Translator.GetText(ContextTranslationFile, "IntroHelpOK", Localization) +
                            "', 'introHelp');";
            ClientScriptProxy.Current.RegisterStartupScript(this, GetType(), "introHelp", script, true);
            chkShowIntroHelp.Checked = true;
            chkShowIntroHelp.Attributes.Add("onclick", "toggleHelp();");
            Response.Cookies.Add(new HttpCookie("IntroHelpIsDisplayed")
                                     {
                                         Expires = DateTime.Now.AddYears(1),
                                         Value = "true"
                                     });
            var ucIntroHelp = (IntroHelp)Page.LoadControl("~/Admin/IntroHelp.ascx");
            ucIntroHelp.SetLocalization(Localization);
            pnlIntroHelpContainer.Controls.Add(ucIntroHelp);
        }

        public virtual bool IntroHelpDisplayed
        {
            get
            {
                HttpCookie introHelpCookie = Request.Cookies["IntroHelpIsDisplayed"];
                return introHelpCookie != null && introHelpCookie.Value == "true" ? true : false;
            }
        }

        public void SetAvailableSites(IEnumerable<Site> sites)
        {
            rpSites.DataSource = sites;
            rpSites.DataBind();
        }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _details = (RequestDetails)HttpContext.Current.Items["RequestDetails"];
            _presenter = new AdminMasterPresenter(this);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Response.ContentEncoding = Encoding.UTF8;
            Response.HeaderEncoding = Encoding.UTF8;
            head.Controls.Add(new iLibRegistrator());
            head.Controls.AddAt(1, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/Main.css"" />"));
            head.Controls.AddAt(2, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/MainBox.css"" />"));
            head.Controls.AddAt(3, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/ErrorBox.css"" />"));
            head.Controls.AddAt(4, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/Buttons.css"" />"));
            head.Controls.AddAt(5, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/Dialogs.css"" />"));
            head.Controls.AddAt(6, new LiteralControl(@"<link rel=""stylesheet"" type=""text/css"" href=""Admin/Css/PopupMenu.css"" />"));
            if (Page.IsPostBack)
                return;
            form1.Action = Url.FoldersAndPage + Url.Querystring;
            _presenter.Initialize();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            litHeading.Text = HeadingText;
            if (HeadingIcon != null)
                imgIcon.ImageUrl = HeadingIcon;
            else
                imgIcon.Visible = false;
            Page.Validate();
            pnlError.Visible = !Page.IsValid;
            hlHelp.NavigateUrl = "http://www.fredium.com/documentation/" + (Page as AdminPage).HelpPage;
            if (!Page.IsPostBack)
                _presenter.LogVisitedAdminUrl(Request.Url.AbsoluteUri, HeadingText, HeadingIcon);
            _presenter.GetAvailableSites();
            baseTag.Attributes.Add("href", Url.FullPath);
            Page.Header.Controls.AddAt(0,
                                       new LiteralControl("<script type=\"text/javascript\" src=\"" +
                                                          ConfigurationManager.AppSettings["jQueryPath"] +
                                                          "\"></script>"));
            litActiveSessionCount.Text = Application["ActiveSessionCount"].ToString();
        }

        protected void rpSites_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var site = (Site)e.Item.DataItem;
            var litDomain = (Literal)e.Item.FindControl("litDomain");
            var lbSite = (LinkButton)e.Item.FindControl("lbSite");
            litDomain.Text = site.Domain;
            lbSite.CommandArgument = site.ID.ToString();
        }

        protected void lbLogout_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("~/ssoauth.ashx?action=logout");
        }

        protected void lbLocalization_Click(object sender, EventArgs e)
        {
            _presenter.SetCurrentLocalization((sender as LinkButton).CommandArgument);
            Response.Redirect(_details.RequestedUrl);
        }

        protected void lbSite_Click(object sender, EventArgs e)
        {
            string newDomain = _presenter.SetCurrentSite(int.Parse((sender as LinkButton).CommandArgument));
            Response.Redirect("http://" + newDomain + "/admin/");
        }

        protected void btnToggleShowIntroHelp_Click(object sender, EventArgs e)
        {
            _presenter.ToggleShowIntroHelp();
        }
    }
}